import http from './request'
import {ElMessage, ElLoading} from 'element-plus'
import router from "@/router";
import {removeUserInfo} from "./auth";

export function baseAjax (paramObj) {
  let url = paramObj.url
  let successHandle = paramObj.success
  let responseType = paramObj.responseType
  let failHandle = paramObj.fail
  let finallyHandle = paramObj.finally
  let type = paramObj.type ? paramObj.type : 'get'
  let data = paramObj.data
  let params = {
    url: url,
    method: type
  }
  if (type === 'get') {
    params.params = http.addParam(data)
  } else {
    // params.data = http.addData(data)
    params.data = data
  }
  if (responseType) {
    params.responseType = responseType
  }
  if (!successHandle) {
    successHandle = defaultSuccessHandle
  }
  if (paramObj.showLoad) {
    showLoading()
  }

  http(params).then((data) => {
    if (data && data.success) {
      successHandle(data)
    } else if (data.code === 401) {
      let message = data.msg ? data.msg : data.message
      ElMessage.error(message)
      removeUserInfo()
      router.push({
        path: '/login',
        query: {
          code: 'login'
        }
      })
    } else if (data.code === 600) {
      if (!failHandle) {
      } else {
        failHandle(data)
      }
    } else {
      let message = data.msg ? data.msg : data.message
      ElMessage.error(message)
      if (!failHandle) {
      } else {
        failHandle(data)
      }
    }
  }).finally(() => {
    if (paramObj.showLoad) {
      hideLoading()
    }
    if (finallyHandle) {
      finallyHandle()
    }
  }).catch(err => console.log('err', err))
}

function defaultSuccessHandle(){
  // Message.success('操作成功')
}

let loading
function showLoading () {
  loading = ElLoading.service({
    lock: false,
    text: '',
    background: 'rgba(0, 0, 0, 0)'
  })
}

function hideLoading () {
  if(loading) {
    loading.close()
    loading = null
  }
}
